package com.org.manhu.chargehelper.ui;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.org.manhu.chargehelper.ChargeApplication;
import com.org.manhu.chargehelper.R;
import com.org.manhu.chargehelper.broadcastreceiver.UpdateMoneyReceiver;
import com.org.manhu.chargehelper.broadcastreceiver.UpdateNickNameReceiver;
import com.org.manhu.chargehelper.constant.Constant;
import com.org.manhu.chargehelper.custom.BatteryCharger;
import com.org.manhu.chargehelper.custom.ExpandableTextView;
import com.org.manhu.chargehelper.custom.ImageBigPopwindow;
import com.org.manhu.chargehelper.custom.RoundCornersImageView;
import com.org.manhu.chargehelper.tools.ApkInfoUtils;
import com.org.manhu.chargehelper.tools.AppManager;
import com.org.manhu.chargehelper.tools.FileUtil;
import com.org.manhu.chargehelper.tools.JsonUtil;
import com.org.manhu.chargehelper.tools.LoadImage;
import com.org.manhu.chargehelper.tools.SerializableMap;
import com.org.manhu.chargehelper.tools.Sever;
import com.org.manhu.chargehelper.tools.SharedPreferncesUtil;
import com.org.manhu.chargehelper.tools.StringUtils;
import com.org.manhu.chargehelper.tools.ToastUtils;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

/**
 * @文件名：DetialActivity.java
 * @包名：com.org.manhu.chargehelper.ui
 * @作者：李朋辉 @QQ：892839211
 * @创建时间：2015年2月5日 上午9:48:25
 *
 * @描述：
 */
public class DetialActivity extends Activity implements OnClickListener {

	private ImageView backIv, userInfoMoreIv;
	private Button cashOutBtn, exchangeBtn;

	private LinearLayout galleryArray;
	Integer[] images = { R.drawable.pic01, R.drawable.pic02, R.drawable.pic03,
			R.drawable.pic04, R.drawable.pic05 };
	DecimalFormat df = new DecimalFormat("0.00");

	private RoundCornersImageView appIconIv;
	private TextView appNameTv, awardTv, sizeTv;
	private Button downBtn;
	private TextView appSummaryTv;

	private TextView userNameTv, awardNumTv;

	private Map<String, String> detialMap;

	private BatteryCharger battery;

	private UpdateNickNameReceiver mReceiver;
	private UpdateMoneyReceiver receivers;
	private ImageBigPopwindow imagebigPopwindow;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_details);
		AppManager.getAppManager().addActivity(this);

		SerializableMap sm = (SerializableMap) getIntent()
				.getSerializableExtra("appinfo");
		detialMap = sm.getMap();

		init();

		mReceiver = new UpdateNickNameReceiver(userNameTv);
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constant.ACTION_UPDATE_NICKNAME);
		registerReceiver(mReceiver, filter);

		receivers = new UpdateMoneyReceiver(awardNumTv);
		IntentFilter filters = new IntentFilter();
		filter.addAction(Constant.ACTION_UPDATE_MONEY);
		registerReceiver(receivers, filters);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		setData();
		awardNumTv.setText(SharedPreferncesUtil.getMoney(this) + "");
		userNameTv.setText(SharedPreferncesUtil.getNickName(this));
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(mReceiver);
		unregisterReceiver(receivers);
	}

	/**
	 * @描述：
	 */
	private void setData() {
		// TODO Auto-generated method stub

		LoadImage.LoadBigPic(detialMap.get("IcoUrl"), appIconIv);
		appNameTv.setText(detialMap.get("AppName"));
		awardTv.setText("安装奖励：" + detialMap.get("UserPrice") + "元");
		String size = df.format(Float.parseFloat(detialMap.get("Size"))
				/ (1024 * 1024))
				+ "M";
		sizeTv.setText(detialMap.get("Tag") + " | " + size);
		appSummaryTv.setText(detialMap.get("Digest"));

		List<String> list = JsonUtil.parseImageList(detialMap.get("ImgList"));
		List<String> imageList = new ArrayList<String>();
		for (int i = 0; i < list.size(); i++) {

			String imagePath = "file://" + Constant.RESOURCE_PATH
					+ detialMap.get("AppID") + "/"
					+ StringUtils.getFileName(list.get(i));
			imageList.add(imagePath);
			galleryArray.addView(insertImage(imagePath, i));
		}
		imagebigPopwindow = new ImageBigPopwindow(this, imageList);
	}

	/**
	 * @描述：初始化，设置监听
	 */
	private void init() {
		backIv = (ImageView) findViewById(R.id.title_back);
		cashOutBtn = (Button) findViewById(R.id.tixian_btn);
		cashOutBtn.setVisibility(View.GONE);
		exchangeBtn = (Button) findViewById(R.id.exchange_btn);
		battery = (BatteryCharger) findViewById(R.id.battery_charge);
		userInfoMoreIv = (ImageView) findViewById(R.id.user_info_more);
		galleryArray = (LinearLayout) findViewById(R.id.galleryArray);
		userNameTv = (TextView) findViewById(R.id.user_name);
		awardNumTv = (TextView) findViewById(R.id.user_award_num);
		awardNumTv.setText(SharedPreferncesUtil.getMoney(this) + "");
		userNameTv.setText(SharedPreferncesUtil.getNickName(this));

		appIconIv = (RoundCornersImageView) findViewById(R.id.detial_app_icon);
		appNameTv = (TextView) findViewById(R.id.activity_details_app_name);
		awardTv = (TextView) findViewById(R.id.activity_details_app_reward);
		sizeTv = (TextView) findViewById(R.id.activity_details_app_size);
		downBtn = (Button) findViewById(R.id.activity_detail_down_btn);
		appSummaryTv = (TextView) findViewById(R.id.activity_detial_app_summary);

		if (ChargeApplication.isBoxConnected) {
			battery.setVisibility(View.VISIBLE);
			battery.startChargerAnim();
		}

		userNameTv.setOnClickListener(this);
		backIv.setOnClickListener(this);
		userInfoMoreIv.setOnClickListener(this);
		downBtn.setOnClickListener(this);
		cashOutBtn.setOnClickListener(this);
		exchangeBtn.setOnClickListener(this);

		// appSummaryTv
		// .setText("《天天跑酷》十一矿仅有9M,无需联网即可运行的横版跑酷游戏。秉承《天天酷跑》、《旋风跑跑（WindRunner）》等游戏的优点，并在难度和操作体验上加以改善。画面清新，风格酷炫可爱，4款多变场景让你体验从沙漠穿越到北极的爽快。死亡还在点击复活？那就OUT了！快来体验宠物复生主人的无敌功能吧！让我们摆脱网络的束缚，变身九尾狐骑乘剑齿虎，在法老王的金字塔下尽情奔跑吧！");
		// for (int i = 0; i < images.length; i++) {
		// galleryArray.addView(insertImage(images[i], i));
		// }
	}

	// 原有方法加载本地资源
	private View insertImage(Integer id, int Rnum) {
		LinearLayout layout = new LinearLayout(getApplicationContext());
		layout.setLayoutParams(new LayoutParams(250, 370));
		layout.setGravity(Gravity.CENTER);
		ImageView imageView = new ImageView(getApplicationContext());
		imageView.setLayoutParams(new LayoutParams(240, 360));
		imageView.setOnClickListener(this);
		imageView.setId(Rnum);
		imageView.setBackgroundResource(id);

		layout.addView(imageView);
		return layout;
	}

	// 加载网络资源
	private View insertImage(String address, int Rnum) {
		LinearLayout layout = new LinearLayout(getApplicationContext());
		int width = (int) (ChargeApplication.getScreenWidth() / 2);
		int height = (int) (ChargeApplication.getScreenHeight() / 2.5);
		layout.setLayoutParams(new LayoutParams(250, 370));
		layout.setGravity(Gravity.CENTER);
		ImageView imageView = new ImageView(getApplicationContext());

		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(240, 360);
		lp.setMargins(16, 0, 0, 0);

		imageView.setId(Rnum);
		imageView.setOnClickListener(this);
		if (Rnum != 0) {
			imageView.setLayoutParams(lp);
		} else {
			imageView.setLayoutParams(new LayoutParams(240, 360));
		}
		Log.d("TAG", "图片路径：：" + address);
		LoadImage.LoadBigPic(address, imageView);
		// layout.addView(imageView);
		return imageView;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() >= 0 && v.getId() < 10) {
			imagebigPopwindow.showPopupWindow(backIv);
			imagebigPopwindow.currentimage(v.getId());
			return;
		}
		switch (v.getId()) {
		case R.id.title_back:
			this.finish();
			break;
		case R.id.tixian_btn:
			Intent it = new Intent(this, CashOutActivity.class);
			startActivity(it);
			break;
		case R.id.exchange_btn:
			Intent its = new Intent(this, ScanActivity.class);
			startActivity(its);
			break;
		case R.id.user_info_more:
			Intent intent = new Intent(this, CenterActivity.class);
			startActivity(intent);
			break;
		case R.id.user_name:
			Intent ite = new Intent(this, ModifyNickNameActivity.class);
			ite.putExtra("nickname", userNameTv.getText().toString());
			startActivity(ite);
			break;
		case R.id.activity_detail_down_btn:
			ChargeApplication.offlineInstallList.put(
					detialMap.get("PackageName"), detialMap.get("AppID"));
			Sever.getInstance().sendMessageToClient(
					StringUtils.installJson(detialMap.get("AppID")));
			ToastUtils.showShort(this, "正在安装");
			break;
		}
	}

}
